use sample_redis::{network, Backend};
use tokio::net::TcpListener;
use tracing::{info, warn};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt::init();

    let addr = "0.0.0.0:6390";
    info!("simple redis server is listening on {}", addr);
    let listener = TcpListener::bind(addr).await?;

    let backend = Backend::new();
    loop {
        let (stream, dst_addr) = listener.accept().await?;
        info!("accept connection from {}", dst_addr);
        let backend_cloned = backend.clone();
        tokio::spawn(async move {
            match network::stream_handler(stream, backend_cloned).await {
                Ok(_) => info!("Connection from {} is handled successfully", dst_addr),
                Err(e) => warn!("Handle error from {}: {:?}", dst_addr, e),
            }
        });
    }
}
